﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using GMusicBox.Core;
using GMusicBox.Core.Setting;

namespace GMusicBox
{
    static class Program
    {
        static frmMain f;
        static StreamWriter sw;

        /// <summary>
        /// 这是应用程序的入口点
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();

            Helper.UpdateHash(true);
            MainSetting.Update();
            StandardSetting.Update();
            LyricShowSetting.Update();
            FXSetting.Update();

            if (!Helper.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\"))
                CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\true");

            Application.SetCompatibleTextRenderingDefault(false);

            bool run;
            System.Threading.Mutex m = new System.Threading.Mutex(true, "hjkcaiAndMyCreat.GoogleMusicBox", out run);

            int id;
            bool runone = EnrollHandle(out id);
            if (runone)
            {
                sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\@" + Process.GetCurrentProcess().Id.ToString());
                sw.Write("something");

                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\Config"))
                {
                    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox") || Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox").Length == 0)
                    {
                        Helper.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox");
                        CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\true");
                        Directory.CreateDirectory(Settings.SettingSavePath + "\\Config\\Configs\\");
                    }
                }

                Helper.CreateDirectory(FXSetting.DspLocation);

                if (!File.Exists(Settings.SettingSavePath + "\\Config\\Downloads.xml"))
                {
                    Directory.CreateDirectory(Settings.SettingSavePath + "\\Config\\");
                    File.CreateText(Settings.SettingSavePath + "\\Config\\Downloads.xml").Close();
                    File.WriteAllText(Settings.SettingSavePath + "\\Config\\Downloads.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\r\n<Downloads>\r\n</Downloads>");
                }

                try
                {
                    f = new frmMain();
                    Control.CheckForIllegalCrossThreadCalls = false;
                    if (StandardSetting.ShowWelcome)
                    {
                        frmWelcome fw = new frmWelcome();
                        fw.ShowDialog();

                        while (!fw.close) Application.DoEvents();
                    }

                    Application.Run(f);

                    MainSetting.Save();
                    StandardSetting.Save();
                    LyricShowSetting.Save();
                    FXSetting.Save();

                    Application.Exit();
                }
                catch (Exception ex)
                {
                    string s = "对不起，谷歌音乐盒出现了无法处理的异常，请联系客服以便帮助我们解决此问题。";
                    s += "\n\n" + ex.ToString();
                    MessageBox.Show(s, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                finally
                {
                    sw.Close();
                    sw.Dispose();
                    if (f != null && f.fder != null && f.fder.dwr != null)
                        f.fder.dwr.Stop();
                    try { File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\@" + Process.GetCurrentProcess().Id.ToString()); }
                    catch { }
                }
            }
            else
            {
                Process p = Process.GetProcessById(id);
                ShowWindowAsync(p.MainWindowHandle, 1);
                SetForegroundWindow(p.MainWindowHandle);
            }
        }

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        public static string[] Charts
        {
            get { return new string[] { "chinese_new_songs_cn", "ea_new_songs_cn", "chinese_songs_cn", "ea_songs_cn", "jk_songs_cn", "pop_songs_cn", "rock_songs_cn", "hip-hop_songs_cn", "soundtrack_songs_cn", "ethnic_songs_cn", "latin_songs_cn", "rnb_songs_cn", "country_songs_cn", "folk_songs_cn", "soul_songs_cn", "easy-listening_songs_cn", "jnb_songs_cn" }; }
        }

        public static void CreatHiddenProfile(string filename)
        {
            try
            {
                File.Create(filename);
                FileInfo fi = new FileInfo(filename);
                fi.Attributes = FileAttributes.Hidden | FileAttributes.System;
            }
            catch { }
        }

        public static void CreatHiddenProfile(string filename, byte[] bytes)
        {
            try
            {
                File.WriteAllBytes(filename, bytes);
                FileInfo fi = new FileInfo(filename);
                fi.Attributes = FileAttributes.Hidden | FileAttributes.System;
            }
            catch { }
        }

        private static void DeleteExcessTempFile()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\";
            string[] files = Directory.GetFiles(path);
            for (int i = 0; i < files.Length; i++)
            {
                string f = Path.GetFileName(files[i]);
                if (f[0] == '@')
                {
                    try
                    {
                        int id = int.Parse(f.Substring(1));
                        Process.GetProcessById(id);
                        File.Delete(files[i]);
                    }
                    catch (Exception e)
                    {
                        if (!(e is IOException))
                            File.Delete(files[i]);
                    }
                }
            }
        }

        private static bool EnrollHandle(out int id)
        {
            DeleteExcessTempFile();

            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\";
            string[] files = Directory.GetFiles(path, "@*");
            if (files.Length > 0)
            {
                id = int.Parse(Path.GetFileName(files[0]).Substring(1));
                return false;
            }
            else
            {
                id = -1;
                return true;
            }
        }

        public static void AddTask(Song[] s)
        {
            f.AddTask(s);
        }

        public static void ConfigCannotRead(Exception ex)
        {
            //提示用户配置文件无法读取并重置配置
            if (VTaskDialog.CanUseTankDialog())
                VTaskDialog.ShowTaskDialog("对不起，谷歌音乐盒在初始化时出现了错误，现在将重置配置文件。\n如果还是无法启动，请联系开发人员，并将程序根目录下的\'GMusicBox.log\'发送至开发人员。\n\n感谢您的使用。", "提示", "谷歌音乐盒已崩溃", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
            else MessageBox.Show("对不起，谷歌音乐盒在初始化时出现了错误，现在将重置配置文件。\n如果还是无法启动，请联系开发人员，并将程序根目录下的\'GMusicBox.log\'发送至开发人员。\n\n感谢您的使用。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            try { Directory.Delete(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\Config\\Configs\\", true); }
            catch { }
            try { Directory.Delete(Application.StartupPath + "\\Config\\Configs\\", true); }
            catch { }

            CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\true");
            File.WriteAllText(Application.StartupPath + "\\GMusicBox.log", ex.ToString(), System.Text.Encoding.Default);

            if (VTaskDialog.CanUseTankDialog())
                VTaskDialog.ShowTaskDialog("现在您可以手动重新启动谷歌音乐盒了。", "提示", "操作已完成", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Information);
            else MessageBox.Show("现在您可以手动重新启动谷歌音乐盒了。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
